package com.heyqing.topic.RemoveDuplicates_0026;

import java.util.*;
import java.util.stream.Collectors;

/**
 * ClassName:RemoveDuplicates
 * Package:com.heyqing.topic.RemoveDuplicates_0026
 * Description:
 *
 * @Date:2024/9/5
 * @Author:Heyqing
 */
public class RemoveDuplicates {


    /**
     * 删除有序数组中的重复项
     *
     * @param nums
     * @return
     */
    public int removeDuplicates(int[] nums) {
        Stack<Integer> stack = new Stack<>();
        stack.push(nums[0]);
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] != stack.peek()) {
                stack.push(nums[i]);
            }
        }
        List<Integer> collect = stack.stream().collect(Collectors.toList());
        for (int i = 0; i < collect.size(); i++) {
            nums[i] = collect.get(i);
        }
        return collect.size();
    }

    public static void start() {
        RemoveDuplicates removeDuplicates = new RemoveDuplicates();
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入数组长度：");
        int length = sc.nextInt();
        int[] nums = new int[length];
        for (int i = 0; i < length; i++) {
            System.out.print("第" + (i + 1) + "个数：");
            nums[i] = sc.nextInt();
        }
        System.out.print("原数组:");
        for (int num : nums) {
            System.out.print(num + " ");
        }
        System.out.println();
        int count = removeDuplicates.removeDuplicates(nums);
        System.out.print("处理后:");
        for (int i = 0; i < count; i++) {
            System.out.print(nums[i] + " ");
        }

    }
}
